<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket测试页面</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }

        .container {
            border: 1px solid #ddd;
            padding: 20px;
            border-radius: 5px;
            background-color: #f9f9f9;
        }

        h1 {
            color: #333;
        }

        .input-group {
            margin-bottom: 15px;
        }

        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }

        input {
            width: 100%;
            padding: 8px;
            box-sizing: border-box;
            margin-bottom: 10px;
        }

        button {
            background-color: #4CAF50;
            color: white;
            padding: 10px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
        }

        button:hover {
            background-color: #45a049;
        }

        #status {
            margin-top: 15px;
            padding: 10px;
            background-color: #f0f0f0;
            border-radius: 4px;
        }

        #baseMessages {
            height: 300px;
            overflow-y: auto;
            border: 1px solid #ddd;
            padding: 10px;
            margin-top: 15px;
            background-color: white;
        }

        .baseMessage {
            margin-bottom: 10px;
            padding: 5px;
            border-bottom: 1px solid #eee;
        }

        .baseMessage.self {
            color: blue;
        }

        .baseMessage.system {
            color: green;
            font-style: italic;
        }

        .baseMessage.error {
            color: red;
        }
    </style>
</head>

<body>
    <div class="container">
        <h1>WebSocket测试页面</h1>

        <div class="input-group">
            <label for="userId">您的用户ID:</label>
            <input type="text" id="userId" placeholder="请输入您的用户ID" value="user1">
        </div>

        <div class="input-group">
            <label for="serverUrl">服务器地址:</label>
            <input type="text" id="serverUrl" placeholder="WebSocket服务器地址" value="ws://localhost:4646/chat">
        </div>

        <button id="connectBtn">连接</button>
        <button id="disconnectBtn" disabled>断开连接</button>

        <div id="status">
            状态: 未连接
        </div>

        <div class="input-group">
            <label for="recipientId">接收者ID:</label>
            <input type="text" id="recipientId" placeholder="请输入接收者ID" value="user2">
        </div>

        <div class="input-group">
            <label for="baseMessage">消息内容:</label>
            <input type="text" id="baseMessage" placeholder="请输入消息内容" value="Hello WebSocket!">
        </div>

        <button id="sendBtn" disabled>发送消息</button>

        <div id="baseMessages">
            <!-- 消息将显示在这里 -->
        </div>
    </div>

    <script>
        let socket = null;
        let userId = document.getElementById('userId').value;
        let serverUrl = document.getElementById('serverUrl').value;

        const connectBtn = document.getElementById('connectBtn');
        const disconnectBtn = document.getElementById('disconnectBtn');
        const sendBtn = document.getElementById('sendBtn');
        const status = document.getElementById('status');
        const baseMessages = document.getElementById('baseMessages');

        // 连接WebSocket
        connectBtn.addEventListener('click', function () {
            userId = document.getElementById('userId').value;
            serverUrl = document.getElementById('serverUrl').value;

            // 确保用户ID不为空
            if (!userId || userId.trim() === '') {
                logMessage('error', '用户ID不能为空');
                return;
            }

            // 添加用户ID作为查询参数
            const urlWithParams = `${serverUrl}?userId=${encodeURIComponent(userId)}`;

            logMessage('system', `正在连接: ${urlWithParams}`);

            try {
                // 先确保之前的连接已关闭
                if (socket) {
                    socket.close();
                }

                socket = new WebSocket(urlWithParams);

                // 增加连接超时处理
                const connectTimeout = setTimeout(function () {
                    if (socket && socket.readyState !== WebSocket.OPEN) {
                        logMessage('error', '连接超时');
                        socket.close();
                    }
                }, 5000); // 5秒超时

                socket.onopen = function (event) {
                    clearTimeout(connectTimeout); // 清除超时计时器
                    logMessage('system', 'WebSocket连接已建立');
                    status.innerHTML = '状态: 已连接';
                    connectBtn.disabled = true;
                    disconnectBtn.disabled = false;
                    sendBtn.disabled = false;

                    // 显示连接详细信息
                    logMessage('system', `连接协议: ${socket.protocol}`);
                    logMessage('system', `扩展: ${socket.extensions}`);
                    logMessage('system', `二进制类型: ${socket.binaryType}`);
                };

                socket.onmessage = function (event) {
                    logMessage('received', event.data);
                };

                socket.onclose = function (event) {
                    clearTimeout(connectTimeout); // 清除超时计时器
                    logMessage('system', `WebSocket连接已关闭`);
                    logMessage('system', `关闭代码: ${event.code}`);
                    logMessage('system', `关闭原因: ${event.reason}`);
                    logMessage('system', `是否正常关闭: ${event.wasClean}`);
                    status.innerHTML = '状态: 未连接';
                    connectBtn.disabled = false;
                    disconnectBtn.disabled = true;
                    sendBtn.disabled = true;
                };

                socket.onerror = function (event) {
                    clearTimeout(connectTimeout); // 清除超时计时器
                    // 增强错误信息显示
                    logMessage('error', 'WebSocket错误');
                    if (event && event.type) {
                        logMessage('error', `错误类型: ${event.type}`);
                    }
                    if (event && event.target && event.target.url) {
                        logMessage('error', `连接URL: ${event.target.url}`);
                    }
                    if (event && event.baseMessage) {
                        logMessage('error', `错误消息: ${event.baseMessage}`);
                    }
                    // 打印整个错误对象
                    console.error('WebSocket错误详情:', event);
                    status.innerHTML = '状态: 连接错误';
                };
            } catch (e) {
                logMessage('error', `连接失败: ${e.baseMessage}`);
                console.error('连接异常详情:', e);
            }
        });

        // 断开连接
        disconnectBtn.addEventListener('click', function () {
            if (socket && socket.readyState === WebSocket.OPEN) {
                socket.close();
            }
        });

        // 发送消息
        sendBtn.addEventListener('click', function () {
            if (socket && socket.readyState === WebSocket.OPEN) {
                const recipientId = document.getElementById('recipientId').value;
                const baseMessage = document.getElementById('baseMessage').value;

                const messageObj = {
                    toUserId: recipientId,
                    content: baseMessage,
                    type: 'text'
                };

                const messageStr = JSON.stringify(messageObj);
                socket.send(messageStr);
                logMessage('self', `发送: ${messageStr}`);
            } else {
                logMessage('error', 'WebSocket未连接');
            }
        });

        // 记录消息
        function logMessage(type, text) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `baseMessage ${type}`;

            // 美化JSON格式的消息
            try {
                const parsed = JSON.parse(text);
                messageDiv.textContent = `${new Date().toLocaleTimeString()} - ${JSON.stringify(parsed, null, 2)}`;
            } catch (e) {
                messageDiv.textContent = `${new Date().toLocaleTimeString()} - ${text}`;
            }

            baseMessages.appendChild(messageDiv);
            baseMessages.scrollTop = baseMessages.scrollHeight;
        }

        // 页面加载时自动尝试连接
        window.addEventListener('load', function () {
            // 取消自动连接，让用户手动点击连接按钮
            // connectBtn.click();
        });
    </script>
</body>

</html>